﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Criterion;
using NHibernate.Tool.hbm2ddl;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Automapping;
using FluentNHibernate;

namespace WhiteFox.DAlessio.Patterns.Repository
{
    public abstract class NHibernateBase
    {
        static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
        static ISessionFactory _sessionFactory = null;

        static FluentNHibernate.Cfg.FluentConfiguration _configuration = null;

        public static FluentNHibernate.Cfg.FluentConfiguration Configuration
        {
            get
            {
                
                    _configuration = GetConfigure();

                return _configuration;
            }
        }

        private static FluentNHibernate.Cfg.FluentConfiguration GetConfigure()
        {

            _configuration = FluentNHibernate.Cfg.Fluently.Configure()
                                      .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.Is(connectionString)))
//                                     .Server("localhost\\sqlexpress")
//                                    .Database("xxxx")
//                                     .Username("xxxxx")
//                                     .Password("xxxxxxxx")))
                                     //.ExposeConfiguration(c => new SchemaExport(c).Execute(true, true, false))                                     
                                     .Mappings(m => m.FluentMappings.AddFromAssembly(System.Reflection.Assembly.Load(System.Configuration.ConfigurationManager.AppSettings["MappingAssemblyName"])));
            return _configuration;
        }

        public static ISessionFactory CreateSessionFactory()
        {
            
            if(_sessionFactory == null)
                _sessionFactory = Configuration.BuildSessionFactory();
            
            return _sessionFactory;

        }

        public static void BuildSchema()
        {
            //Configuration.ExposeConfiguration(c => new SchemaExport(c).Execute(true, true, true));
            var build = new SessionSource(Configuration);
            build.BuildSchema();
        }

        public static ISession GetNHBSession()
        {
            if (_sessionFactory == null)
            {
                _sessionFactory = CreateSessionFactory();
            }
            return _sessionFactory.OpenSession();
        }

    }
}
